package ee.homework.third;

import java.util.Stack;

/**
 * Postfix calculator implementation - Reverse Polish calculator
 * 
 * @author Kaarel Hanson
 * @since 05.03.2011
 */
public class ReversePolishCalculator {

	public static void main(String[] args) {
		ReversePolishCalculator calc = new ReversePolishCalculator();
		if (args.length > 0) {
			Double result = calc.calculate(args[0]);
			System.out.println("Result: " + result);
		}
	}

	private double calculate(String input) {
		Stack<Double> stack = new Stack<Double>();
		double first, second;
		for (char item : input.toCharArray()) {
			try {
				stack.push(Double.parseDouble(String.valueOf(item)));
			} catch (NumberFormatException e) {
				second = stack.pop();
				first = stack.pop();
				switch (item) {
				case '+':
					stack.push(first + second);
					break;
				case '-':
					stack.push(first - second);
					break;
				case '*':
					stack.push(first * second);
					break;
				case '/':
					stack.push(first / second);
					break;
				}
			}
		}
		return stack.pop();
	}
}
